import { HubConnectionBuilder } from "@aspnet/signalr";
import MsgMethods from "@/consts/MsgMethods";

export default {
  data: function() {
    return { connection: null };
  },
  methods: {
    // 有新房间创建SignalR消息
    onRoomCreate(msg) {
      const room = {
        roomName: msg.roomName,
        roomId: msg.roomId,
        memberCount: 1
      };
      this.roomList.push(room);
    },
    // 有房间被销毁SignalR消息
    onRoomDestroy(msg) {
      const index = this.roomList.findIndex((room, index) => {
        return room.roomId == msg.roomId;
      });
      if (index === -1) return;
      this.roomList.splice(index, 1); // 删除房间
    },
    // 有人离开聊天室
    leaveRoom(leaveMsg) {
      const roomItem = this.roomList.find(room => {
        return room.roomId == leaveMsg.roomId;
      });
      if (roomItem && roomItem.memberCount > 0) roomItem.memberCount--; // 人数递减
    },
    // 有人进入房间
    roomEnter(enterMsg) {
      const roomItem = this.roomList.find(room => {
        return room.roomId == enterMsg.roomId;
      });
      if (roomItem && roomItem.memberCount >= 0) roomItem.memberCount++; // 人数递增
    }
  },
  created() {
    const hub =
    process.env.NODE_ENV == "development" ? "/ws/chatHub" : "/chatHub";
    this.connection = new HubConnectionBuilder().withUrl(hub).build();
    this.connection.on(MsgMethods.RoomCreate, this.onRoomCreate.bind(this));
    this.connection.on(MsgMethods.RoomDestroy, this.onRoomDestroy.bind(this));
    this.connection.on(MsgMethods.RoomLeave, this.leaveRoom.bind(this));
    this.connection.on(MsgMethods.RoomEnter, this.roomEnter.bind(this));
    this.connection.start();
  }
};
